<?php
/**
 * 购物车处理
 */
class CartController extends Controller{
	public function __init(){
		define('__TEMPLATE__',__ROOT__.'/Template/jd');
		if(empty($_SESSION['cart'])){
			$_SESSION['cart']=array(
				'goods'=>array(),
				'totalprice'=>0,
				'totalnum'=>0
			);
		}
	}
	//添加购物车
	public function add(){
		$_GET['sid']=$_GET['id'];
		$sql = "SELECT s.gid,s.price,g.gname,s.sid,g.index_image FROM jz_goods AS g 
		JOIN jz_stock AS s on g.gid=s.gid
		WHERE s.gid={$_GET['gid']}";
		$goods = M()->query($sql);
		$goods=$goods[0];
		$cart=array(
			'sid'=>$goods['sid'],//库存id
			'gid'=>$goods['gid'],//商品id
			'gname'=>$goods['gname'],
			'num'=>$_GET['num'],
			'price'=>$goods['price'],
			'image'=>$goods['index_image']
		);
		$_SESSION['cart']['ngood']=$cart;
		// p($cart);die;
		$_SESSION['cart']['goods'][$_GET['sid']]=$cart;
		//算购物车中所有商品的价格汇总与数量汇总
		$totalPrice=$totalNum=0;
		foreach($_SESSION['cart']['goods'] as $goods){
			$totalNum+=$goods['num'];
			$totalPrice+=$goods['num']*$goods['price'];
		}
		$_SESSION['cart']['totalprice']=$totalPrice;
		$_SESSION['cart']['totalnum']=$totalNum;
		$_SESSION['cart']['nsid']=$_GET['sid'];
		$this->display('Template/jd/jrgwc.html');
	}
	public function cart(){
		$this->display('Template/jd/cart.html');
	}
	public function del(){
		$sid=Q('sid','','intval');
		$totalPrice=$_SESSION['cart']['totalprice']-$_SESSION['cart']['goods'][$sid]['price'];
		$totalNum=$_SESSION['cart']['totalnum']-$_SESSION['cart']['goods'][$sid]['num'];
		$_SESSION['cart']['totalprice']=$totalPrice;
		$_SESSION['cart']['totalnum']=$totalNum;
		unset($_SESSION['cart']['goods'][$sid]);
		$this->display('Template/jd/cart.html');
	}
}










